package com.ruoyi.iot.hikvision;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.OkHttpUtils;
import com.ruoyi.iot.domain.CameraPreviewModel;
import com.ruoyi.iot.domain.PioltDevice;
import com.ruoyi.iot.domain.YsDeviceCtrlResponse;
import com.ruoyi.iot.hikvision.ys.*;
import com.ruoyi.iot.service.IPioltDeviceService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@Service
public class YsDeviceService {
    @Autowired
    private YsTokenService ysTokenService;

    @Autowired
    private IPioltDeviceService pioltDeviceService;

    /////////////////////////////////////
    /**
     * 获取萤石token
     * http://open.ys7.com/doc/zh/book/index/user.html
     * https://open.ys7.com/bbs/article/34
     * @return
     */
    //异步添加设备到萤石平台
    public void addDeviceSync(PioltDevice deviceCamera) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        body.put("validateCode",deviceCamera.getDeviceNumber());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/add")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsResponse ysResponse = JSONObject.parseObject(body,YsResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")){
                                    //成功
                                    deviceCamera.setDeviceState(PioltDevice.StateRegistOk);
                                    deviceCamera.setDeviceStateRemarks("注册成功");
                                }else {
                                    deviceCamera.setDeviceState(PioltDevice.StateRegistError);
                                    deviceCamera.setDeviceStateRemarks("注册失败： 失败码 "+ysResponse.getCode()+"  失败原因 "+ysResponse.getMsg());
                                }
                                pioltDeviceService.updatePioltDevice(deviceCamera);
                                getDeviceInfoSync(deviceCamera);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    //获取设备信息
    //https://open.ys7.com/doc/zh/book/index/device_select.html#device_select-api2
    public void getDeviceInfoSync(PioltDevice deviceCamera) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/info")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceInfoResponse ysResponse = JSONObject.parseObject(body,YsDeviceInfoResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")&&ysResponse.getData()!=null){
                                    //成功
                                    YsDeviceInfoResponse.DeviceInfo deviceInfo = ysResponse.getData();
                                    deviceCamera.setDeviceModel(deviceInfo.getModel());//设备型号
                                    deviceCamera.setDeviceState(1==deviceInfo.getStatus()?
                                            PioltDevice.device_status_10:PioltDevice.device_status_20);
                                    deviceCamera.setDeviceIsEncrypt(deviceInfo.getIsEncrypt());
                                    deviceCamera.setDeviceAlarmSoundMode(deviceInfo.getAlarmSoundMode());
                                    deviceCamera.setDeviceOfflineNotify(deviceInfo.getOfflineNotify());
                                    deviceCamera.setDeviceCategory(deviceInfo.getCategory());
                                    pioltDeviceService.updatePioltDevice(deviceCamera);
                                    getDeviceChannelInfoSync(deviceCamera);
                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    //https://open.ys7.com/doc/zh/book/index/device_select.html#device_select-api2
    //获取设备通道信息
    public void getDeviceChannelInfoSync(PioltDevice deviceCamera){
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/camera/list")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceChannelResponse ysResponse = JSONObject.parseObject(body,YsDeviceChannelResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")&&ysResponse.getData()!=null){
                                    //成功
                                    ysResponse.getData().stream().parallel().forEach(item->{

                                        deviceCamera.setChannelNo(item.getChannelNo());
                                        deviceCamera.setIpcSerial(item.getIpcSerial());
                                        deviceCamera.setDeviceName(item.getDeviceName());
                                        deviceCamera.setChannelName(item.getChannelName());
                                        //deviceCamera.setStatus(item.getStatus()); int	在线状态：0-不在线，1-在线,-1设备未上报
                                        if(0==item.getStatus()){
                                            deviceCamera.setDeviceState(PioltDevice.device_status_20);
                                        }else if(1==item.getStatus()){
                                            deviceCamera.setDeviceState(PioltDevice.device_status_10);
                                        }else if(-1==item.getStatus()){
                                            deviceCamera.setDeviceState(PioltDevice.device_status_30);
                                        }
//                                        deviceCameraChannel.setPicUrl(item.getPicUrl());
                                        deviceCamera.setIsShared(item.getIsShared());
//                                        deviceCamera.setIsEncrypt(item.getIsEncrypt());
                                        deviceCamera.setVideoLevel(item.getVideoLevel());
                                        deviceCamera.setRelatedIpc(item.isRelatedIpc());
                                        pioltDeviceService.updatePioltDevice(deviceCamera);
                                    });

                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    //https://open.ys7.com/doc/zh/book/index/device_select.html#device_select-api9
    //获取设备文件
    public void getDeviceFiles(PioltDevice deviceCamera) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
//        body.put("startTime", ""+DateUtils.getZeroHourDateOfDate(new Date(),-10).getTime());
//        body.put("startTime", ""+new Date().getTime());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/video/by/time")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceFileResponse ysResponse = JSONObject.parseObject(body,YsDeviceFileResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")&&ysResponse.getData()!=null){
                                    //成功
                                    ysResponse.getData().stream().parallel().forEach(item->{

                                    });

                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    public void deviceCapture(PioltDevice deviceCamera) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        body.put("channelNo",deviceCamera.getChannelNo()+"");
//        body.put("startTime", ""+DateUtils.getZeroHourDateOfDate(new Date(),-10).getTime());
//        body.put("startTime", ""+new Date().getTime());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/capture")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDevicePicResponse ysResponse = JSONObject.parseObject(body,YsDevicePicResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")&&ysResponse.getData()!=null){
                                    //成功
                                    String picUrl = ysResponse.getData().getPicUrl();
                                    if(!StringUtils.isEmpty(picUrl)){
                                        OkHttpUtils.getInstance().init().url(picUrl)
                                                .get().exec(new OkHttpUtils.OnResponse() {
                                            @Override
                                            public void onSuccess(Response response) {
                                                if(response.isSuccessful()){
                                                    processVideoCapture(response,deviceCamera);
                                                }
                                            }

                                            @Override
                                            public void onError(Exception e) {

                                            }
                                        });

                                    }
                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    public void processVideoCapture(Response response,PioltDevice deviceCamera) {
//        try {
//            String fileName = IdGen.uuid()+".jpg";
//            String selfUrl = alibabaFileService
//                    .uploadFile(AlibabaFileService.bucketNameBank,
//                            "camera/"+fileName,
//                            fileName,
//                            response.body().bytes());
//            DeviceCameraFile deviceCameraFile = new   DeviceCameraFile();
//            deviceCameraFile.setDeviceCustomerId(deviceCameraBankCustomer.getId());
//            deviceCameraFile.setType(DeviceCameraFile.type_pic);
//            deviceCameraFile.setCaptureDate(new Date());
//            deviceCameraFile.setUrl(selfUrl);
//            deviceCameraFileService.save(deviceCameraFile);
//            deviceCameraBankCustomer.setDeviceCaptureImage(selfUrl);
//            deviceCameraBankCustomerService.save(deviceCameraBankCustomer);
//            //添加到场景巡视中
//            RiskCustomer customerCurrentRisk = riskCustomerService.
//                    getCustomerCurrentRisk(deviceCameraBankCustomer.getBankCustomerId());
//            if(customerCurrentRisk!=null){
//                BankCustomerInspection bankCustomerInspection = new BankCustomerInspection();
//                bankCustomerInspection.setBank(customerCurrentRisk.getBank());
//                bankCustomerInspection.setBankCustomer(customerCurrentRisk.getBankCustomer());
//                bankCustomerInspection.setBankUser(customerCurrentRisk.getBankUser());
//                bankCustomerInspection.setType(1);
//                bankCustomerInspection.setInspectionDate(new Date());
//                List<FyjfFile> inspectionImages =new ArrayList<>();
//                FyjfFile file = new FyjfFile();
//                file.setUrl(selfUrl);
//                inspectionImages.add(file);
//                bankCustomerInspection.setInspectionImages(inspectionImages);
//                bankCustomerInspection.setFileId(deviceCameraFile.getId());
//                bankCustomerInspectionService.save(bankCustomerInspection);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    //获取设备告警信息
    public void getDeviceAlarm(PioltDevice deviceCamera) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        body.put("pageSize","50");
        body.put("pageStart","0");
        body.put("startTime", ""+ DateUtils.getZeroHourDateOfDate(new Date(),-10).getTime());
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/alarm/device/list")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceAlarmResponse ysResponse = JSONObject.parseObject(body,YsDeviceAlarmResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")&&ysResponse.getData()!=null){
                                    //成功
                                    ysResponse.getData().stream().parallel().forEach(item->{

                                    });

                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    /** 获取设备直播地址
     *
     * https://open.ys7.com/help/1414
     *
     *
     * 预览：ezopen:// [验证码@] open.ys7.com/[deviceSerial]/[channelNo] [.hd].live
     * 地址示例：ezopen://open.ys7.com/203751922/1.hd.live
     * 回放：ezopen:// [验证码@] open.ys7.com/[deviceSerial]/[channelNo] [.hd].rec[?begin= yyyyMMddhhmmss&end= yyyyMMddhhmmss]
     * 地址示例：ezopen://验证码@open.ys7.com/203751922/1.rec?begin=20190317000000&begin=20190317235959
     * @param deviceCamera
     * @return
     */
    public CameraPreviewModel getDeviceOnlinePreview(PioltDevice deviceCamera) {
//        return url[0];
        String previewHdUrl = String.format("ezopen://%s@open.ys7.com/%s/%s.hd.live",
                deviceCamera.getEncryptKey(),
                deviceCamera.getDeviceSeries(),
                deviceCamera.getChannelNo()!=null?deviceCamera.getChannelNo():1);
        String previewFluentUrl = String.format("ezopen://%s@open.ys7.com/%s/%s.live",
                deviceCamera.getEncryptKey(),
                deviceCamera.getDeviceSeries(),
                deviceCamera.getChannelNo()!=null?deviceCamera.getChannelNo():1);
        CameraPreviewModel data = new CameraPreviewModel();
        data.setPreviewHdUrl(previewHdUrl);
        data.setPreviewFluentUrl(previewFluentUrl);
        data.setAccessToken(ysTokenService.getAccessToken());
        return data;
//        if(deviceCamera!=null){
////            data.put("brandPackage",deviceCamera.getBrandPackage());
//            data.setAccessToken(ysTokenService.getAccessToken());
////            String previewHdUrl = String.format("ezopen://%s@open.ys7.com/%s/%s.hd.live",
////                    deviceCamera.getValidateCode(),
////                    deviceCamera.getDeviceSeries(),
////                    deviceCamera.getChannelNo());
////            data.setPreviewHdUrl(previewHdUrl);
////            String previewFluentUrl = String.format("ezopen://%s@open.ys7.com/%s/%s.live",
////                    deviceCamera.getValidateCode(),
////                    deviceCamera.getDeviceSeries(),
////                    deviceCamera.getChannelNo());
////            data.setPreviewFluentUrl(previewFluentUrl);
////		data.put("playbackLocalUrl",String.format("ezopen://%s@open.ys7.com/%s/%s.hd.live", deviceCamera.getDeviceValidateCode(),deviceCamera.getDeviceSerial(),deviceCameraChannel.getChannelNo()));
////		data.put("playbackCloudUrl",String.format("ezopen://%s@open.ys7.com/%s/%s.hd.live", deviceCamera.getDeviceValidateCode(),deviceCamera.getDeviceSerial(),deviceCameraChannel.getChannelNo()));
//        }
//        return data;
    }

    /////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
    //云台控制 https://open.ys7.com/help/59?h=direction
    public void ctrlDirection(PioltDevice deviceCamera,int direction,Integer deviceSpeed) {
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        body.put("channelNo",deviceCamera.getChannelNo()!=null?deviceCamera.getChannelNo()+"":"1");
        body.put("direction",""+direction);
        body.put("speed",""+deviceSpeed);//云台速度：0-慢，1-适中，2-快，海康设备参数不可为0
        body.put("startTime", ""+ DateUtils.getZeroHourDateOfDate(new Date(),-10).getTime());
//        logger.info("-------------ctrlDirection-------------------"+ JSON.toJSONString(body));
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/ptz/start")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
//                            logger.info("-------------ctrlDirection-----success--------------"+ body);
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceCtrlResponse ysResponse = JSONObject.parseObject(body,YsDeviceCtrlResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")){
                                    //成功
                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
//                        logger.info("-------------ctrlDirection-----onError--------------"+e.getMessage());
//                        logger.error("ctrlDirection",e);
                    }
                });
    }

    public void ctrlStop(PioltDevice deviceCamera) {
        //这个接口 和前端调研stop一样
        HashMap<String,String> body = new HashMap<>();
        body.put("accessToken",ysTokenService.getAccessToken());
        body.put("deviceSerial",deviceCamera.getDeviceSeries());
        body.put("channelNo",deviceCamera.getChannelNo()!=null?deviceCamera.getChannelNo()+"":"1");
        //body.put("direction",""+direction);
        OkHttpUtils.getInstance().init()
                .url("https://open.ys7.com/api/lapp/device/ptz/stop")
                .formBodyPost(body)
                .execSync(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            String body = response.body().string();
                            if(!StringUtils.isEmpty(body)){
                                YsDeviceCtrlResponse ysResponse = JSONObject.parseObject(body,YsDeviceCtrlResponse.class);
                                if(ysResponse!=null&&ysResponse.getCode().equals("200")){
                                    //成功
                                }else {

                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Exception e) {
                    }
                });
    }


}
